package com.riber.student.config;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.riber.student.common.Const;
import com.riber.student.common.ResponseCode;
import com.riber.student.common.ResponseResult;
import com.riber.student.util.TokenUtils;
import com.riber.student.vo.output.LoginInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: Riber
 * @date: 2022/10/26 20:43
 * @description:
 */
public class MyAuthorizationInterceptor implements HandlerInterceptor {
//ok
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        HttpSession session = request.getSession();
        //处理预请求问题,浏览器会预先发送一个请求询问服务器状态
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //获取保存在head的token
        String authorization = request.getHeader("Authorization");
        //声明 ObjectMapper om jackson
        ObjectMapper om = new ObjectMapper();
        //从session中取值
        LoginInfoVo is_login = (LoginInfoVo) session.getAttribute(Const.IS_LOGIN);
        //判断是否token有值,session是否存在
        if (StringUtils.isEmpty(authorization) || is_login == null) {
            System.out.println("没有token或者session");
            ResponseResult<Object> rr = ResponseResult.createLoginResponse(ResponseCode.IS_NOT_LOGIN.getCode(),
                    "请先登录", null);
            response.getWriter().println(om.writeValueAsString(rr));
            return false;
        }
        try {
            Claims claims = TokenUtils.parseToken(authorization);
            String jti = (String) claims.get("jti");
            //验证登录是否正常
            if (!jti.equals(is_login.getUserId().toString())) {
                System.out.println("token的用户id和服务器保存的用户id一致");
                ResponseResult<Object> rr = ResponseResult.createLoginResponse(ResponseCode.IS_NOT_LOGIN.getCode(),
                        "请先登录或联系管理员", null);
                response.getWriter().println(om.writeValueAsString(rr));
                return false;
            }
            System.out.println("已有登录信息可以访问");
            //放行
            return true;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            ResponseResult<Object> rr = ResponseResult.createLoginResponse(ResponseCode.IS_NOT_LOGIN.getCode(),
                    "令牌已经过期请重新登录", null);
            response.getWriter().println(om.writeValueAsString(rr));
        } catch (IOException e) {
            e.printStackTrace();
            ResponseResult<Object> rr = ResponseResult.createLoginResponse(ResponseCode.IS_NOT_LOGIN.getCode(),
                    "服务器异常 请重新再试", null);
            response.getWriter().println(om.writeValueAsString(rr));
        }
        return false;
    }
}